package 数据结构与算法.实验二;

public class Stack {
    private static String[] stack;
    private static int length;//当前栈的元素个数
    private static int size;//栈总大小

    Stack(){
        size = 10;
        stack = new String[size];
        length = 0;
    }
    //入栈
    public static void push(String element) throws Exception{
        //System.out.println("element" + element);
        if(length >= size){
           throw new Exception("Stackoverflow");
        }
        stack[length] = element;
        length++;
    }
    //出栈
    public String pop() throws Exception{
         if(length <= 0){
             throw new Exception("Stack is empty");
         }
         //int element = stack[length - 1];
         //length--;
         //return element;
         return stack[--length];
    }

    public String peek(){
        System.out.println("");
        for(length = 0; length < stack.length ;length++){
            if(stack[length].equals("+")){
                addition();
            }else if(stack[length].equals("-")){
                subtraction();
            }else if(stack[length].equals("*")){
                multiplication();
            }else if(stack[length].equals("/")){
                division();
            }
            if(stack[2] == null){
                return "计算结果为 "+stack[0];
            }
        }
        return null;
    }

    public int length(){
        return length;
    }

    public Boolean isEmpty(){
        return length == 0;
    }

    private static void addition(){
        stack[length - 2] = String.valueOf((Integer.parseInt(stack[length - 2])) + (Integer.parseInt(stack[length - 1])));
        arrange();
    }

    private static void subtraction(){
        stack[length - 2] = String.valueOf((Integer.parseInt(stack[length - 2])) - (Integer.parseInt(stack[length - 1])));
        arrange();
    }

    private static void multiplication(){
        stack[length - 2] = String.valueOf((Integer.parseInt(stack[length - 2])) * (Integer.parseInt(stack[length - 1])));
        arrange();
    }

    private static void division(){
        stack[length - 2] = String.valueOf((Integer.parseInt(stack[length - 2])) / (Integer.parseInt(stack[length - 1])));
        arrange();
    }

    //整理栈，删除使用过的数据
    private static void arrange(){
        for(int j = length - 1; j < stack.length;j++){
            if(stack[j]== null){
                break;
            }else {
                stack[j] = stack[j + 2];
            }
        }
        length = 0;
    }

    public void print(){
        System.out.println("-----------------");
        System.out.println("size:" + size);
        System.out.println("length:" + length);
        for(int i = 0;i < length;i++){
            System.out.print(stack[i] + ",");
        }
        System.out.println(" ");
    }
}
